/**
 * 路由缓存
 */
export default {
	namespaced: true,
	state: {
    menuData: [
      {
        label: '首页',
        path: '/index'
      },
      {
        label: 'Echarts demo',
        children: [
          {label: '地图', path: '/echarts/map-chart'},
        ]
      },
      {
        label: '其它',
        children: [
          {label: 'A页面', path: '/others/a'},
          {label: 'B页面', path: '/others/b'}
        ]
      }
    ],  //菜单数据
    cacheViewObjList: [], //页面组件 {path,label,name}
    activeViewPath: ''
  },
  getters: {
    //多维菜单数组转为一维菜单数组，较少不必要的多层循环
    menuDataList(state) {
      const list = state.menuData;
      let newArray = []
      const _format = (arr, parentIndex)=> {
        for (let i = 0; i < arr.length; i++) {
          const item = arr[i];
          let arrayKey = null;
          Object.keys(item).forEach((key)=> {
            if (Object.prototype.toString.call(item[key]) === '[object Array]') {
              arrayKey = key;
            }
          })
          if (arrayKey) {
            _format(item[arrayKey], (parentIndex === undefined ? '': parentIndex+'-')+i)
          } else {
            newArray.push({
              index: (parentIndex === undefined ? '': parentIndex+'-')+i,
              label: item.label,
              path: item.path
            })
          }
        }
      }
      _format(list)
      return newArray;
    },
    //被缓存的页面组件name列表
    cacheViews(state) {
      let arr = state.cacheViewObjList.map(({ name })=> name);
      return arr
    }
  },
  mutations: {
    //存储菜单数据
    setMenuData(state, payload) {
      state.menuData = payload
    },
    addCacheView(state, payload) {
      if (this.getters['RouterCache/cacheViews'].indexOf(payload.name) === -1) {
        state.cacheViewObjList.push(payload)
      }
    },
    //删除缓存tab
    deleteCacheView(state, name) {
      state.cacheViewObjList.splice(this.getters['RouterCache/cacheViews'].indexOf(name), 1)
    },
    setActiveViewName(state, path) {
      state.activeViewPath = path;
    }
  }
}